import Vue  from 'vue';
import Vuex from 'vuex';
import VueResource from 'vue-resource'

Vue.use(VueResource)
Vue.use(Vuex)

export default new Vuex.Store({
	state : {
		userInfo : '',
		ip:'http://172.16.186.8:4000/',
	},
	mutations : {
		setUserInfo(state,payload){
			state.userInfo = payload.userInfo;
		},
	},
	actions: {
		getAndDelMethod(context,payload){
			Vue.http[payload.method](payload.url,{
				timeout : 3000,
				headers : {
					"Authorization" : sessionStorage.getItem('token'),
				},
				params : payload.params,
				before : function(){
					console.log('loading...')
				}
			}).then(function(response){
				// 请求时将新的token保存到sessionStorage
				if(response.headers.get('authorization')){
					sessionStorage.setItem('token', response.headers.get('authorization'));
				}
				//执行回调函数
				payload.callback(response)	
			}).catch(function(response){
				// token过期
				if(response.status == 401 && response.body.status == 'fail'){
					return router.push('/login')
				}
				// token失效(登出)
				if(response.status == 403 && response.body.status == 'fail'){
					return router.push('/login')
				}

				return console.log(response)
			});
		},

		// 其他方法
		httpMethod(context, payload) {
			Vue['http'][payload.method]( payload.url, payload.data, {
				timeout : 3000,
				headers : {
					// "Content-Type" : "application/x-www-form-urlencoded",
					"Authorization" : sessionStorage.getItem('token'),
				},
				before : function(request){
					console.log('loading...')
				},
				//设置为表单提交的方式，不然没效果
				emulateJSON : true,
			}).then(function(response){
				// 请求时将新的token保存到sessionStorage
				if(response.headers.get('authorization')){
					sessionStorage.setItem('token', response.headers.get('authorization'));
				}

				payload.callback(response)	
			}).catch(function(response){
				// token过期
				if(response.status == 401 && response.body.status == 'fail'){
					return router.push('/login')
				}
				// token失效(登出)
				if(response.status == 403 && response.body.status == 'fail'){
					return router.push('/login')
				}

				return console.log(response)
			});
		}


	}
})